package com.janwen.j2ee.mail;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

/**
 * refer:http://wenson.iteye.com/blog/348564
 * @author janwen
 * Aug 31, 2012
 */
@Service("springEmail")
public class SpringEmailService {

	@Autowired
	private JavaMailSenderImpl javaMailSender;

	private SimpleMailMessage mailMessage;
	
	@Autowired
	public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage){
		this.mailMessage = simpleMailMessage;
	}
	public void sendEmail(String[] to, String body, String title) {
		SimpleMailMessage mail = new SimpleMailMessage(); // <span
															// style="color: #ff0000;">注意SimpleMailMessage只能用来发送text格式的邮件</span>
		try {
			String from = javaMailSender.getUsername();
			for(int i=0;i<to.length;i++){
				mail.setTo(to[i]);// 接受者
			}
			mail.setFrom(from);// 发送者,这里还可以另起Email别名，不用和xml里的username一致
			mail.setSubject(title);// 主题
			mail.setText(body);// 邮件内容
			javaMailSender.send(mail);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void sendEmailByTemplate(String body){
		SimpleMailMessage message = new SimpleMailMessage(mailMessage);
		message.setSentDate(new Date());
		message.setText(body);
		javaMailSender.send(message);
	}
}
